package com.jy.mybatis;

import org.apache.log4j.Logger;
import org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3Impl;

/**
 * 更改后缀及下划线转换
 * @author jiangyan
 *
 */
public class GeneratorSpectTable extends IntrospectedTableMyBatis3Impl {

	private Logger logger = Logger.getLogger(GeneratorSpectTable.class);

	@Override
	protected void calculateJavaClientAttributes() {

		super.calculateJavaClientAttributes();

		StringBuffer sb = new StringBuffer();
		sb.append(this.calculateJavaClientInterfacePackage());
		sb.append('.');
		sb.append(this.generateDomainName());
		sb.append("Dao");
		String mapperName = sb.toString();
		logger.debug("Rename MyBatis3JavaMapperTypeName:" + mapperName);
		super.setMyBatis3JavaMapperType(mapperName);

	}

	@Override
	protected void calculateXmlAttributes() {
		super.calculateXmlAttributes();
		StringBuffer sb = new StringBuffer();
		sb.append(this.calculateJavaClientInterfacePackage());
		sb.append('.');
		sb.append(this.generateDomainName());
		sb.append("Mapper");
		String mapperName = sb.toString();
		logger.debug("Rename MyBatis3XmlMapperTypeName:" + mapperName);
		super.setMyBatis3XmlMapperFileName(this.generateDomainName() + "Mapper.xml");

	}

	@Override
	public void calculateModelAttributes(){
		super.calculateModelAttributes();
		String packageName = super.calculateJavaModelPackage();
		StringBuilder sb = new StringBuilder();
		sb.append(packageName);
		sb.append('.');
		String newDomainName = this.generateDomainName();
		sb.append(newDomainName);
		sb.append("Entity");
		logger.debug("Rename setBaseRecordType:" + newDomainName);
		this.setBaseRecordType(sb.toString());
	}

	protected String generateDomainName() {
		String newDomainName = this.fullyQualifiedTable.getIntrospectedTableName();
		int index = newDomainName.indexOf("_");
		if (index > 0) {
			newDomainName = camel4underline(newDomainName.substring(index + 1));
		} else {
			newDomainName = this.fullyQualifiedTable.getDomainObjectName();
		}
		return newDomainName;
	}

	/**
	 * formEntity -> formEntity
	 * user_role -> UserEntity
	 * FormEntity -> &ormEntity (错误)
	 * 首字母大写并且替换下划线并将下一个字母大写
	 * @param param
	 * @return
	 */
	public static String camel4underline(String str) {
		StringBuffer sbf = new StringBuffer();
		// 如果字符串包含 下划线
		if (str.contains("_")) {
			String[] split = str.split("_");
			for (int i = 0, index = split.length; i < index; i++) {	
				sbf.append(camel4underline(split[i]));
			}
		} else {// 字符串不包含下划线  转换成字符数组
			char[] ch = str.toCharArray();
			// 判断首字母是否是字母
			if (ch[0] >= 'a' && ch[0] <= 'z') {
				// 利用ASCII码实现大写
				ch[0] = (char) (ch[0] - 32);
			}
			// 添加进字符串缓存区
			sbf.append(ch);
		}
		return sbf.toString();
	}
}